package org.yufan.controller;


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.yufan.admin.bean.PicUploadResult;
import org.yufan.service.ConfigService;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import java.awt.image.BufferedImage;
import java.io.File;
import java.util.UUID;

@Controller
@RequestMapping("/pic")
public class UploadController {

    private Logger LOGGER=LoggerFactory.getLogger(UploadController.class);

    @Autowired
    private ConfigService configService;

    @RequestMapping(value = "/upload",method = RequestMethod.POST)
    @ResponseBody
    public PicUploadResult upload(@RequestParam  MultipartFile uploadFile, HttpServletRequest request){

        //封装结果集，告诉调用者上传结果
        PicUploadResult picUploadResult=new PicUploadResult();
        try {

            //获取文件的后缀
            String filename = uploadFile.getOriginalFilename();
            String end = filename.substring(filename.lastIndexOf("."));

            LOGGER.info("上传的文件名称:{}",filename);

            //生成新的文件名
            String uuid_name = UUID.randomUUID().toString().replaceAll("-", "") + end;
            LOGGER.info("生成的文件名称为:{}",uuid_name);
            File file = new File(configService.path + File.separator + uuid_name);

            LOGGER.info("上传文件的配置的路径为:{}",configService.path);

            //保存图片到服务器
            uploadFile.transferTo(file);

            //获取宽和高
            BufferedImage image=ImageIO.read(file);
            if(image!=null){
                picUploadResult.setError(0);
                picUploadResult.setUrl(configService.url+uuid_name);
                LOGGER.info("上传文件后访问的路径为:{}",configService.url+uuid_name);
                picUploadResult.setWidth(image.getWidth()+"");
                picUploadResult.setHeight(image.getHeight()+"");
            }else{
                //上传失败
                LOGGER.error("上传失败,上传的文件名为:{},上传者的ip地址为:{}",filename,request.getRemoteAddr());
                picUploadResult.setError(1);
                file.delete();
            }
        }catch (Exception e){
            LOGGER.error("上传失败,具体的错误信息为{}",e.getMessage());
            picUploadResult.setError(1);
        }
       return picUploadResult;
    }


}
